import java.util.HashMap;
import java.util.Map;
public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}



import java.util.HashMap;
        import java.util.Map;
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public Map<Integer,Integer> map = new HashMap<>();
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        for (int i = 0; i < inorder.length; i++) {
            map.put(inorder[i],i);
        }
        return myBuildTree(preorder,inorder,0,preorder.length-1,0,inorder.length-1);
    }

    private TreeNode myBuildTree(int[] preorder,int[] inorder,int preorder_left,int preorder_right,int inorder_left,int inorder_right) {
        if (preorder_left>preorder_right || inorder_left > inorder_right) return null;
        int midIndex = map.get(preorder[preorder_left]);
        TreeNode root = new TreeNode(preorder[preorder_left]);
        int gap = midIndex - inorder_left;
        root.left = myBuildTree(preorder,inorder,preorder_left+1,gap+preorder_left,inorder_left,midIndex-1);
        root.right = myBuildTree(preorder,inorder,gap+preorder_left+1,preorder_right,midIndex+1,inorder_right);
        return root;
    }

}